package thread;


//第一种，通过检查interrupted()判断是否被中止
class ResponsiveUI extends Thread {

	private static volatile double d = 1;

	public ResponsiveUI() {
		//setDaemon(true);
		start();
	}

	@Override
	public void run() {
		while (d > 0) {
			d = d + (Math.E + Math.PI) / d;
			if(interrupted()) {
				System.out.println(getName() + " has been interrupted");
				return;
				// throw new RuntimeException(getName() + " has been interrupted");
			}
		}
	}

	public double getProgress() {
		return d;
	}
}

class UnresponsiveUI {
	private volatile double d = 1;

	public UnresponsiveUI() throws Exception {
		while (d > 0) {
			d = d + (Math.E + Math.PI) / d;
		}
		System.in.read(); // Never gets here
	}
}

public class SimuleUI{
	public static void main(String[] args) throws Exception{
		// ! new UnresponsiveUI(); // Must kill this process
		System.out.println("input a char:");
		ResponsiveUI rui = new ResponsiveUI();
		Thread.sleep(300);
		System.in.read();
		System.out.println(rui.getProgress()); // Shows progress
		rui.interrupt();
	}
}

// 第二种，只要interrupt()，不管之后睡还是正在睡、之后wait还是正在wait，都要抛异常
class ti extends Thread{
	public ti() {
		start();
	}
	
	@Override
	public void run() {
		interrupt();
		synchronized(Object.class) {
			try {
				// wait(100); 异常哦：current thread not owner
				Object.class.wait(100);
			} catch (InterruptedException e) {
				System.out.println(interrupted());
				e.printStackTrace();
			}
		}

		interrupt();
		try {
			sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(interrupted());
		
		try {
			sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		new ti();
	}
}